#include "rel.h"

// Arrays to store messages and the file name
char receiveMessageBuffer [MSG_LEN];
char sendMessageBuffer [MSG_LEN];
char fileName [FILENAME_LEN];

// Sequence number and file name length
unsigned long long currentSequenceNumber;
int fileNameLength;

// Toggles debugging on or off
int debug = false;
  
// Stopwatch
time_t start;

// Declares receiver as flag = 0;
int sender = false;

// Socket file descriptor
int socketfd;

// Stores Port Number to bind on (receiver's port)
unsigned short receiverPort;

// Sender Information
unsigned short senderPort;
char ipAddress[20];
  
// Timestamp of last response from other application
time_t lastResponseTime = 2147483647;

// Size of Message in Send Buffer
int sendMessageSize = 0;

// Size of Message in Receive Buffer
int receiveMessageSize = 0;

// Number of Retransmissions
int numRetransmits = 0;

// Mutex Lock
pthread_mutex_t mutexLock = PTHREAD_MUTEX_INITIALIZER;

// Turn off timer
int timerOn = true;

// Boolean to test if transmission successful
int successfulTransfer = false;

main (int argc, char * argv[]){
 
  // CommandLine Arguments
  commandLineRecv(argc, argv, &receiverPort);

  // Configure Sender for sending/receiving over network
  socketfd = networkConfigure(receiverPort);
  
  // Declare initial sequence number
  currentSequenceNumber = 0;
  
  // Network structs 
  struct sockaddr sa;
  struct addressPort ap;
  
  // Create thread to keep track of responses
  createTimerThread();
  
  // number of bytes received through network
  int bytesReceived;
  
  // send test
  int testNumber = 0;


  
  while(true){
    if (debug){
    printf("\nWaiting to Receive from Sender...\n");
    }
    // Call Recvfrom to wait for incoming messages from sender
    bytesReceived = receiveUDP (socketfd, (unsigned char *) receiveMessageBuffer, MSG_LEN, &sa);
    
    // Message will be loaded into receiveMessageBuffer
    if (debug){
	    printf("Sending #%d\n", testNumber++);
      printf("Bytes Received: %d", bytesReceived);
      printMessage(receiveMessageBuffer, bytesReceived);
    }
    
    // Assign sender's address and port to global ipAddress and port variables
    getAddressPort(&sa, &ap );
    
    parseMessage();
	  sendUDP(ipAddress, senderPort, socketfd, sendMessageBuffer, sendMessageSize);  

  }
  

  
}